#!/bin/sh
set -e

PHP_FPM_CONF="/usr/local/etc/php-fpm.d/www.conf"
PHP_CHILD_MEM=${PHP_CHILD_MEM:-20}  # 每个 PHP 子进程平均占用内存（MB）

# 自动检测 cgroup 版本并获取内存限制
get_container_memory_limit() {
  if [ -f /sys/fs/cgroup/memory.max ]; then
    # cgroup v2: 读取 memory.max
    cat /sys/fs/cgroup/memory.max | awk '{if ($1 ~ /^[0-9]+$/) print $1/1048576; else print 2048}'
  elif [ -f /sys/fs/cgroup/memory/memory.limit_in_bytes ]; then
    # cgroup v1
    cat /sys/fs/cgroup/memory/memory.limit_in_bytes | awk '{print $1/1048576}'
  else
    # 默认值（如在 Docker Desktop for Mac 上）
    echo ${PHP_MAX_MEM:-2048}
  fi
}

TOTAL_MEM=$(get_container_memory_limit)
echo "检测到容器内存限制: ${TOTAL_MEM}MB"

# 留出 20% 给系统和 Nginx 使用
AVAILABLE_MEM=$(expr $TOTAL_MEM \* 80 / 100)
MAX_CHILDREN=$(expr $AVAILABLE_MEM / $PHP_CHILD_MEM)

echo "可用内存（扣除系统和 Nginx）: ${AVAILABLE_MEM}MB"
echo "每个 PHP-FPM 子进程预计占用: ${PHP_CHILD_MEM}MB"
echo "自动设置 pm.max_children = ${MAX_CHILDREN}"

# 修改 PHP-FPM 配置
sed -i "s/;*pm.max_children =.*/pm.max_children = ${MAX_CHILDREN}/" ${PHP_FPM_CONF}
sed -i "s/;*pm =.*/pm = dynamic/" ${PHP_FPM_CONF}
sed -i "s/;*pm.start_servers =.*/pm.start_servers = $(expr $MAX_CHILDREN / 4)/" ${PHP_FPM_CONF}
sed -i "s/;*pm.min_spare_servers =.*/pm.min_spare_servers = $(expr $MAX_CHILDREN / 8)/" ${PHP_FPM_CONF}
sed -i "s/;*pm.max_spare_servers =.*/pm.max_spare_servers = $(expr $MAX_CHILDREN / 2)/" ${PHP_FPM_CONF}

# 删除 .env 文件（如果存在）
ENV_FILE="/var/www/html/quick_curd/.env"
if [ -f "$ENV_FILE" ]; then
  rm "$ENV_FILE"
  echo "删除 $ENV_FILE，使用环境变量配置或者自定义安装"
fi

# 启动 php-fpm
echo "Starting php-fpm..."
php-fpm -F &

# 启动 nginx
echo "Starting nginx..."
nginx -g 'daemon off;'
